package security

import (
	"crypto/tls"
	"log"
	"time"

	"golang.org/x/crypto/acme/autocert"
)

type CertManager struct {
	Manager       *autocert.Manager
	CacheDir      string
	Domains       []string
	RenewBefore   time.Duration // 默认30天前开始续期
	CheckInterval time.Duration // 默认12小时检查一次
}

func NewCertManager(domains []string, cacheDir string) *CertManager {
	m := &autocert.Manager{
		Cache:      autocert.DirCache(cacheDir),
		Prompt:     autocert.AcceptTOS,
		HostPolicy: autocert.HostWhitelist(domains...),
	}

	return &CertManager{
		Manager:       m,
		CacheDir:      cacheDir,
		Domains:       domains,
		RenewBefore:   30 * 24 * time.Hour, // 30天
		CheckInterval: 12 * time.Hour,      // 12小时
	}
}

func (cm *CertManager) StartAutoRenew() {
	ticker := time.NewTicker(cm.CheckInterval)
	defer ticker.Stop()

	for range ticker.C {
		// 这里需要实现具体的证书检查和续期逻辑
		// 可以调用cm.Manager.GetCertificate来触发续期
		log.Println("Checking certificates for renewal...")
	}
}

func (cm *CertManager) GetTLSConfig() *tls.Config {
	return &tls.Config{
		GetCertificate:           cm.Manager.GetCertificate,
		PreferServerCipherSuites: true,
		MinVersion:               tls.VersionTLS12,
		CurvePreferences: []tls.CurveID{
			tls.X25519,
			tls.CurveP256,
		},
	}
}
